/* * * * M A P V I S I O N   L I C E N S E  *****************************************************************
 *
 * This MapVision software is © Filip Zavadil 2013. It is licensed under the LGPL license.
 * This MapVision software dynamically links to unmodified Qt5 Library.
 *
 * The Qt5 Library is © 2013 Qt® and/or its subsidiary(-ies), and is licensed under the
 * GNU Lesser General Public License version 2.1 with Qt® LGPL exception version 1.1.
 * Qt5 library is free software; you can redistribute it and/or modify it under the terms of the
 * GNU Lesser General Public License, version 2.1, as published by the Free Software Foundation.
 * Qt5 library is provided “AS IS”, without WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
 *
 * As an additional permission to the GNU Lesser General Public License version 2.1, the object
 * code form of a “work that uses the Library” may incorporate material from a header file that is
 * part of the Library. You may distribute such object code under terms of your choice,
 * provided that: (i) the header files of the Library have not been modified; and (ii)
 * the incorporated material is limited to numerical parameters, data structure layouts, accessors,
 * macros, inline functions and templates; and (iii) you comply with the terms of Section 6 of the
 * GNU Lesser General Public License version 2.1.
 *
 * Moreover, you may apply this exception to a modified version of the Library, provided that such
 * modification does not involve copying material from the Library into the modified Library’s header
 * files unless such material is limited to (i) numerical parameters; (ii) data structure layouts;
 * (iii) accessors; and (iv) small macros, templates and inline functions of five lines or less in length.
 *
 * Furthermore, you are not required to apply this additional permission to a modified version of the Library.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this package;
 * if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

 * The source code for Qt 5.X SDK is available from Qt Project here:
 * http://download.qt-project.org/official_releases/qtcreator/2.7/2.7.0/qt-creator-2.7.0-src.zip.
 *
 * ****************************** M A P V I S I O N    S O F T W A R E  ************************************
 *
 * Author:       Filip Zavadil
 * Description:  Software for displaying and exporting map tiles.
 * The sources and executables of MapVision software are available:
 *    - from project hosting on CodePlex.com :   http://mapvision.codeplex.com
 *    - from GIT repositories on Gitorious.org:  https://gitorious.org/mapvision
 * Visit MapVision fanpage on Facebook.com:      https://www.facebook.com/pages/Mapvision/631827753513935
 *
 * *********************************************************************************************************
*/

#include "mapdocumet.h"
#include "ui_mapdocumet.h"
#include <QDebug>


MapDocumet::MapDocumet(QMainWindow *parent, QList<Layer *>* layers_) :
    QDialog(parent), ui(new Ui::MapDocumet),layers(layers_),mainWindow(parent)
{
    map= parent->findChild<MapView *>("map");
    label = parent->findChild<QLabel *>("labelDocummentName");
    ui->setupUi(this);
    document = new QDomDocument("map");
    mapFile = new QFile("");

    connect(map,SIGNAL(mapUpdated(QPointF,int,int)),this,SLOT(unsaved(QPointF,int,int)));
}

MapDocumet::~MapDocumet()
{
    delete ui;
}

bool MapDocumet::open2()
{
QFileDialog fileDialog;
    QString path=settings.value("main/document").toString();
    QString fileString = fileDialog.getOpenFileName(this, tr("Open MapVision document"),
                                                      path,
                                                      tr("MapVision document (*.mvd);;All files(*.*)"));


mapFile = new QFile(fileString);
    if (!mapFile->open(QIODevice::ReadWrite))return false;
    if (!document->setContent(mapFile)) return false;

    settings.setValue("main/document",fileString);
    return this->feed();

}

bool MapDocumet::save(bool isSaveAs)
{
    label->setText(label->text().remove("*"));

    if (layers->size()==0)
    {
        QMessageBox msgBox;
                    msgBox.setText(tr("No map layers was loaded!"));
                    msgBox.exec();
        return false;
    }
    QFile *file;
    QDomDocument saveDocument("MapVisionDocument");

    QDomProcessingInstruction xmlProcessingInstruction = saveDocument.createProcessingInstruction("xml", "version=\"1.0\"");
    saveDocument.appendChild(xmlProcessingInstruction);
    QString fileName;


    if (isSaveAs || mapFile->fileName()==""){
        QFileDialog fileDialog;
        fileDialog.setDefaultSuffix("mvd");
        fileName = fileDialog.getSaveFileName(this, tr("Save image map"), settings.value("main/saveDocument").toString(),
                                                        tr("MapVision Document (*.mvd);;"
                                                           "All files (*.*);;"));
        if (fileName=="") return false;

        file = new QFile(fileName);

    } else  {
        file = new QFile(mapFile->fileName());
    }


    if (!file->open(QIODevice::ReadWrite | QIODevice::Text | QIODevice::Truncate)) return false;

    originLonLat = map->getCenterLonLat();
    originZoom = map->getZoom();
    viewScale = map->getViewScale();
    QDomElement mapEl = saveDocument.createElement("map");
    mapEl.setAttribute("name",projectName);
    mapEl.setAttribute("desc",description);
    QString createdString = toXmlDateTime(created);
    if (createdString=="") createdString=toXmlDateTime(QDateTime::currentDateTime());
    qDebug()<<createdString;
    mapEl.setAttribute("created",createdString);
    mapEl.setAttribute("saved",toXmlDateTime(QDateTime::currentDateTime()));
    mapEl.setAttribute("owner",owner);
    mapEl.setAttribute("longtitude",QString::number(originLonLat.x()));
    mapEl.setAttribute("latitude",QString::number(originLonLat.y()));
    mapEl.setAttribute("zoom",QString::number(originZoom));
    mapEl.setAttribute("scale",QString::number(viewScale));

    saveDocument.appendChild(mapEl);

    QDomElement layersEl = saveDocument.createElement("layers");
    mapEl.appendChild(layersEl);

    for (int i = 0; i < layers->size(); i++ )
    {
        QDomElement layerEl = saveDocument.createElement("layer");
        Layer * layer = layers->value(i);

        layerEl.setAttribute("type",layer->getLayerTypeString(layer->getLayerType()));
        layerEl.setAttribute("name",layer->getLayerName());
        layerEl.setAttribute("source",layer->getSource());
        QPointF lonLat = layer->getLonlatOrigin();
        layerEl.setAttribute("longtitude",QString::number(lonLat.x()));
        layerEl.setAttribute("latitude",QString::number(lonLat.y()));
        layerEl.setAttribute("zoom",QString::number(layer->getZoomOrigin()));
        layerEl.setAttribute("zValue",QString::number(layer->getZvalue()));
        layerEl.setAttribute("opacity",QString::number(layer->getOpacity()*100));
        layersEl.appendChild(layerEl);
    }

    QTextStream textStream(file);
    textStream << saveDocument.toString() ;
    file->close();

    settings.setValue("main/saveDokument",fileName);

    label->setToolTip(file->fileName());
    QString fName= file->fileName().right(file->fileName().length()-file->fileName().lastIndexOf("/")-1);
    label->setText(fName);
    mapFile->setFileName(file->fileName());

    return true;

}

bool MapDocumet::feed()
{
    QDomElement mapEl = document->documentElement();
    QDomElement layersEl = mapEl.elementsByTagName("layers").item(0).toElement();

    projectName = mapEl.attribute("name");
    description = mapEl.attribute("desc");
    QString createdString = mapEl.attribute("created");
    QString savedString = mapEl.attribute("saved");
    owner = mapEl.attribute("owner");
    originLonLat = QPointF(mapEl.attribute("longtitude").toDouble(),mapEl.attribute("latitude").toDouble());
    originZoom = mapEl.attribute("zoom").toInt();
    created=created.fromString(createdString,"yyyy'-'MM'-'dd'T'HH:mm:ss");
    viewScale = mapEl.attribute("scale").toInt();
    saved=saved.fromString(savedString,"yyyy'-'MM'-'dd'T'HH:mm:ss");

        map->setCenterLonLat(originLonLat);
        map->setZoom(originZoom);
        map->setViewScale(viewScale);

    label->setToolTip(mapFile->fileName());
    QString fName= mapFile->fileName().right(mapFile->fileName().length()-mapFile->fileName().lastIndexOf("/")-1);
    label->setText(fName);


    return this->feedLayers(layersEl.childNodes());


}

bool MapDocumet::feedLayers(QDomNodeList nodeList)
{
    int size = nodeList.size();

    for (int i = 0; i < size; i++ )
    {
        QDomElement layerEl = nodeList.item(i).toElement();
        QString name = layerEl.attribute("name");
        QString source = layerEl.attribute("source");
        QPointF lonlat = QPointF(layerEl.attribute("longtitude").toDouble(),layerEl.attribute("latitude").toDouble());
        int zoom = layerEl.attribute("zoom").toInt();
        Layer temp(mainWindow);
        Layer::layerType type= temp.getLayerTypeFromString(layerEl.attribute("type"));
        int transparency = layerEl.attribute("opacity").toInt();
        int zValue = layerEl.attribute("zValue").toInt();

        this->addLayer(type,name,source,lonlat,zoom,zValue,transparency);

    }

    return true;
}

QString MapDocumet::toXmlDateTime(QDateTime dateTime)
{
    return dateTime.toString("yyyy'-'MM'-'dd'T'HH:mm:ss");
}

bool MapDocumet::addLayer(Layer::layerType type, QString name, QString source, QPointF lonlat, int zoom, int zValue, int transparency)
{
    if (type == Layer::TMSlocal)
    {
        layers->push_back(new LayerTILESlocal(mainWindow,Layer::TMSlocal,name,source,lonlat,zoom,zValue,transparency));
        return true;
    }
    else if (type == Layer::TMSonline)
    {
        layers->push_back(new LayerTILESonline(mainWindow,Layer::TMSonline,name,source,lonlat,zoom,zValue,transparency));
        return true;
    }
    else if (type == Layer::WMTSlocal)
    {
        layers->push_back(new LayerTILESlocal(mainWindow,Layer::WMTSonline,name,source,lonlat,zoom,zValue,transparency));
        return true;
    }
    else if (type == Layer::WMTSonline)
    {
        layers->push_back(new LayerTILESonline(mainWindow,Layer::WMTSonline,name,source,lonlat,zoom,zValue,transparency));
        return true;
    }
    else if (type == Layer::MBtiles)
    {
        layers->push_back(new LayerSQLite(mainWindow,Layer::MBtiles,name,source,lonlat,zoom,zValue,transparency));
        return true;
    } else if (type == Layer::GeoImage){
        layers->push_back(new LayerIMG(mainWindow,Layer::GeoImage,name,source,lonlat,zoom,zValue,transparency));
        return true;
    }
    return false;
}

void MapDocumet::unsaved(QPointF,int,int)
{
    if (!label->text().contains("*")) label->setText(label->text()+"*");
}
